/**
* 系统管理  设备绑定审核
*/
<template>
  <div style="width: 100%;height: 100%">
    <!-- 搜索筛选 -->
    <el-row :model="formInline" style="height: 5%;width: 100%;display: flex;align-items: center;">
      <el-col :span="0.5" style="margin-right: 0.5vw">
        <el-text size="large">搜索:</el-text>
      </el-col>
      <el-col :span="4" style="display: flex;align-items: center;justify-content: center;">
        <el-input size="large" v-model="formInline.userName" placeholder="请输入申请人姓名或手机号"></el-input>
      </el-col>
      <el-col :span="4" style="display: flex;">
        <el-button size="large" style="background-color:#04c1a5;color:#fff" @click="searchByName()">
          <font-awesome-icon icon="fas fa-search" />
          <span style="margin-left:1vh">查询</span>
        </el-button>
      </el-col>
      <el-col :span="16">
      </el-col>
    </el-row>
    <el-row style="
    background-color: white;
    height: 35%;
    margin-top: 2vh;
    margin-bottom: 10px;
    border-radius: 10px;
    box-shadow: 0 0 10px rgba(0, 0, 0, 0.1);">
      <filter-list :filter-rows="rows" @updateList="updateList"/>
    </el-row>
    <!-- 分页组件5%-->
    <el-row style="display: flex;justify-content: flex-end;align-items: center;height: 5%;width: 100%;margin-bottom: 10px">
      <el-pagination
          v-model:current-page="pageParam.pageNo"
          v-model:page-size="pageParam.pageSize"
          v-model:total="pageParam.totalCount"
          :page-sizes="[5, 10, 15, 20]"
          :small="false"
          :disabled="false"
          :background="true"
          layout="total,sizes, prev, pager, next, jumper"
          :total="100"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
      />
    </el-row>
    <!--列表-->
    <el-table
        :header-cell-style=" { background: '#F7FBFE' , color: '#000' , 'text-align': 'center' }"
        size="large"
        :cell-style="{'text-align':'center'}"
        style="width: 100%;height: 50%"
        :data="applyData"
        v-loading="loading"
        highlight-current-row
        class="customer-table"
        border
        element-loading-text="拼命加载中">
<!--      <el-table-column sortable prop="id" label="申请编号" width="150" >-->
<!--      </el-table-column>-->
      <el-table-column sortable prop="name" label="申请人" width="180">
      </el-table-column>
      <el-table-column sortable prop="username" label="电话号码" width="180">
      </el-table-column>
      <el-table-column sortable prop="serialCode" label="申请设备序列号" width="200">
        <template #default="scope">
          <div>{{removeSubstring(scope.row.serialCode,"ynu",false,true)}}</div>
        </template>
    </el-table-column>
      <el-table-column prop="status" label="申请状态" width="150">
      </el-table-column>

      <el-table-column sortable prop="applicationTime" label="申请时间" width="200">
        <template v-slot="scope">
          {{ formatDateTime(scope.row.applicationTime) }}
        </template>
      </el-table-column>
<!--      <el-table-column sortable prop="expirationDate" label="申请使用时长" width="150">-->
<!--      </el-table-column>-->
<!--
      <el-table-column sortable prop="processingTime" label="处理时间" width="150">
        <template v-slot="scope">
          {{ formatDateTime(scope.row.processingTime) }}
        </template>
      </el-table-column>
      -->
      <el-table-column align="center" fixed="right" label="操作" min-width="200">
        <template v-slot="scope">
          <el-button size="default" style="background-color:#edf7f6;color:#4CAF50;" @click="AuditBind(scope.row.id,1)">
            <font-awesome-icon icon="fas fa-check-circle" />
            <span style="margin-left:1vh">同意绑定</span>
          </el-button>
          <el-button size="default" type="danger" style="" @click="showConfirmationDialog(scope.row.id,-1)">
            <font-awesome-icon icon="fas fa-ban" />
            <span style="margin-left:1vh">拒绝绑定</span>
          </el-button>
        </template>
      </el-table-column>
    </el-table>
    <el-dialog
        v-model="checkDialogVisible"
        title="警告"
        width="500"
        align-center
        style="padding: 0"
    >
      <el-text size="large">是否拒绝绑定？</el-text>
      <template #footer>
        <div >
          <el-button @click="cancelOperation">取消</el-button>
          <el-button type="primary" style="background-color: #04c1a5;border: 0" @click="confirmOperation">确定</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import {FontAwesomeIcon} from "@fortawesome/vue-fontawesome";
import {onMounted, ref} from 'vue';

import doctor from "@/api/doctor.js";
import {ElMessage} from "element-plus";
import FilterList from "@/components/tableViews/filterList.vue";
import {removeSubstring} from "@/utils/strFormat.js";
const loading = ref(false);
const title = ref('添加');
const editForm = ref({
  deptId: '',
  deptName: '',
  deptNo: '',
  token: localStorage.getItem('logintoken')
});
const formInline = ref({
  userName:''
});
const applyData = ref([]);

const checkDialogVisible = ref(false);
const pageParam = ref({
  // status:1,
  pageNo:1,
  pageSize:10,
  totalCount:10,
  totalPages:10,
  nextPage:0,
  prePage:0,
  hasPre:false,
  hasNext:true,
});

onMounted(() => {
  getDataList();
});
//分页方法
const handleCurrentChange = (newPage)=>{
  pageParam.value.pageNo = newPage;
  const auditBindingQuery = {
    status:'',
    // status:0,
    currentTime:'',
    applicationTimeEnd:'',
    processingTimeEnd:'',
    pageIndex: pageParam.value.pageNo - 1,
    pageSize: pageParam.value.pageSize
  };
  // 调用更新方法
  updateBindingDeviceQuery(rows.value, auditBindingQuery);
  //执行查询
  requestAuditBindingData(auditBindingQuery);
}
const handleSizeChange = ()=>{
  const auditBindingQuery = {
    pageIndex: pageParam.value.pageNo - 1,
    pageSize: pageParam.value.pageSize,
  }
  updateBindingDeviceQuery(rows,auditBindingQuery)
  requestAuditBindingData(auditBindingQuery)
}
const updatePageParams = (pageData) =>{
  pageParam.value.pageNo = pageData.pageNo;
  pageParam.value.pageSize = pageData.pageSize;
  pageParam.value.totalCount = pageData.totalCount;
  pageParam.value.totalPages = pageData.totalPages;
  pageParam.value.nextPage = pageData.nextPage;
  pageParam.value.hasNext = pageData.hasNext;
  pageParam.value.prePage = pageData.prePage;
  pageParam.value.hasPre = pageData.hasPre;
}

//更新查询条件
const updateBindingDeviceQuery=(rows, bindingDeviceQuery)=> {
  // bindingDeviceQuery.status = updateSelectedValue(rows[0].buttons);
  // bindingDeviceQuery.currentTime = getCurrentDate();
  // bindingDeviceQuery.applicationTimeEnd = updateTime(rows[1].buttons, bindingDeviceQuery.currentTime);
  // // bindingDeviceQuery.processingTimeEnd = updateTime(rows[2].buttons, bindingDeviceQuery.currentTime);
  // if (bindingDeviceQuery.applicationTimeEnd === null && bindingDeviceQuery.processingTimeEnd===null){
  //   bindingDeviceQuery.currentTime = null;
  // }
  const statusButtons = rows[0].buttons;
  const selectedStatus = updateSelectedValue(statusButtons);
  // 确保 status 的值为 0 或 -1
  bindingDeviceQuery.status = selectedStatus === 0 || selectedStatus === -1 ? selectedStatus : null;

  bindingDeviceQuery.currentTime = getCurrentDate();
  bindingDeviceQuery.applicationTimeEnd = updateTime(rows[1].buttons, bindingDeviceQuery.currentTime);

  if (bindingDeviceQuery.applicationTimeEnd === null && bindingDeviceQuery.processingTimeEnd === null) {
    bindingDeviceQuery.currentTime = null;
  }
}
const formatDateTime=(dateTimeString)=> {
  const date = new Date(dateTimeString);
  const year = date.getFullYear();
  const month = String(date.getMonth() + 1).padStart(2, '0');
  const day = String(date.getDate()).padStart(2, '0');
  const hour = String(date.getHours()).padStart(2, '0');
  const minute = String(date.getMinutes()).padStart(2, '0');
  const second = String(date.getSeconds()).padStart(2, '0');
  return `${year}-${month}-${day} ${hour}:${minute}:${second}`;
}
const getCurrentDate = ()=> {
  const now = new Date();
  const year = now.getFullYear();
  const month = String(now.getMonth() + 1).padStart(2, '0');
  const day = String(now.getDate()).padStart(2, '0');
  return `${year}-${month}-${day}`;
}
const updateSelectedValue=(buttons)=> {
  for (const button of buttons) {
    if (button.selected) {
      return button.value;
    }
  }
  return null;
}
const updateTime=(buttons, currentDate)=> {
  for (const button of buttons) {
    if (button.selected) {
      if (button.value === null) {
        return null;
      } else {
        const time = new Date();
        time.setDate(time.getDate() - button.value);
        const year = time.getFullYear();
        const month = String(time.getMonth() + 1).padStart(2, '0');
        const day = String(time.getDate()).padStart(2, '0');
        return `${year}-${month}-${day}`;
      }
    }
  }
  return currentDate; // 默认取当前时间
}
const getStatusText = (statusCode) => {
  switch (statusCode) {
    case 0:
      return "申请绑定";
    // case 1:
    //   return "已绑定";
    case -1:
      return "拒绝绑定";
    default:
      return "未知状态";
  }
};

//查询过滤
const rows = ref([
  { label: '状态', buttons: [
      { text: '-全部-', value: null, selected: true },
      { text: '申请绑定', value: 0, selected: false },
      // { text: '已绑定', value: 1, selected: false },
      { text: '拒绝绑定', value: -1, selected: false },
    ] },


  { label: '申请时间', buttons: [
      { text: '-全部-', value: null,selected: true },
      { text: '刚刚',value: 1, selected: false },
      { text: '最近1天', value: 2,selected: false },
      { text: '最近7天', value: 7,selected: false },
      { text: '最近两周', value: 14,selected: false },
      { text: '最近1个月', value: 30,selected: false },
      { text: '最近3个月', value: 90,selected: false },
      { text: '最近一年', value: 365,selected: false },
      { text: '一年以上', value: null,selected: false },
    ] },
    /*
  { label: '处理时间', buttons: [
      { text: '-全部-', value: null,selected: true },
      { text: '刚刚',value: 1, selected: false },
      { text: '最近1天', value: 2,selected: false },
      { text: '最近7天', value: 7,selected: false },
      { text: '最近两周', value: 14,selected: false },
      { text: '最近1个月', value: 30,selected: false },
      { text: '最近3个月', value: 90,selected: false },
      { text: '最近一年', value: 365,selected: false },
      { text: '一年以上', value: null,selected: false },
    ] },

     */


]);
const updateList = (rows) =>{
  const auditBindingQuery = {
    status: '',
    // status: 0,
    currentTime:'',
    applicationTimeEnd:'',
    processingTimeEnd:'',
    pageIndex: pageParam.value.pageNo - 1,
    pageSize: pageParam.value.pageSize
  };
  // 调用更新方法
  updateBindingDeviceQuery(rows, auditBindingQuery);
  requestAuditBindingData(auditBindingQuery);
}

//绑定弹窗
const userId = ref(null);
const deviceId = ref(null);
const applyId = ref(null)
const status = ref(null);
const showConfirmationDialog = (id, stat) => {
  applyId.value = id;
  status.value = stat;
  checkDialogVisible.value = true;
};
const cancelOperation = () => {
  checkDialogVisible.value = false;
};
const confirmOperation = () => {
  checkDialogVisible.value = false;
  AuditBind(applyId.value, status.value);
};
const AuditBind = (applyId,StatusCode)=>{
  const bindingDeviceAuditEditQuery = {
    applyId:applyId,
    status:StatusCode
  }
  doctor.bindingDeviceAudit(bindingDeviceAuditEditQuery).then((res)=>{
    if (res.data.code === 200){
      ElMessage.success("操作成功")
      getDataList()
    }else{
      console.log(res)
      ElMessage.error(res.data.msg)
    }
  }).catch((err)=>{
    ElMessage.error("出错了，请重试")
    console.log(err)
  })
}

//请求列表
const getDataList = ()=>{
  const AuditBindingQuery = {
    status: updateSelectedValue(rows.value[0].buttons),
    pageIndex: pageParam.value.pageNo - 1,
    pageSize: pageParam.value.pageSize
  };
  requestAuditBindingData(AuditBindingQuery)
}
const requestAuditBindingData = (auditBindingQuery)=>{
  loading.value = true
  doctor.bindingDeviceAuditSearch(auditBindingQuery)
      .then((res) => {
        if (res.data.code === 200) {
          // 将状态码转换为中文描述
          applyData.value = res.data.data.result
              // 过滤掉不符合条件的数据
              .filter(apply => apply.status === 0 || apply.status === -1)
              .map(apply => ({
            ...apply,
            status: getStatusText(apply.status)
          }));
        }
        updatePageParams(res.data.data);
      })
      .catch((err) => {
        console.log(err);
      })
      .finally(()=>{
        loading.value = false
      })
  ;
}

//条件查询
const searchByName = ()=>{
  const auditBindingQuery = {
    status: updateSelectedValue(rows.value[0].buttons),
    pageIndex: pageParam.value.pageNo - 1,
    pageSize: pageParam.value.pageSize,
  }
  if (formInline.value.userName.length === 11){
    auditBindingQuery.userName = formInline.value.userName
  }else{
    auditBindingQuery.name = formInline.value.userName
  }
  requestAuditBindingData(auditBindingQuery)
}
</script>

<style scoped>
.user-search {
  margin-top: 20px;
}
.userRole {
  width: 100%;
}
/* :deep(.customer-no-border-table th){
    border:none;
}
:deep(.customer-no-border-table td,.customer-no-border-table th.is-leaf)  {
  border:none;
} */
::v-deep .customer-table th{
  border:none;
}
::v-deep .customer-table td,.customer-table th.is-leaf {
  border:none;
}
::v-deep .el-pagination.is-background .el-pager li:not(.disabled).active {
  /* background-color:#04c1a5; */
  background-color: green;
  color: #fff;
}
::v-deep .el-pagination.is-background .el-pager li:not(.disabled) {
  background-color: #04c1a5;
}
</style>